node('master') {
    // modify node_name and ip address fields 取消[全局安全设置]-[防止跨站点请求伪造]//
    // ---------------------------------------//
    def workDir = '/home/tomcat/workspace/jenkins-agent'
    def executor_count = '2'
    def cret ='tomcat_private_key'

    try{
        wrap([$class: 'MaskPasswordsBuildWrapper',
              varPasswordPairs: [[password: "${params.jenkins_user}", var: 'jenkins_user'],
                                 [password: "${params.jenkins_pwd}", var: 'jenkins_pwd']]]){
            stage('Add Jenkins slave') {
                addNode(params.nodeLabel, executor_count,workDir);
            }

            stage('Get Agent jar') {
                def url = params.jenkins_url + "/jnlpJars/agent.jar";
                getAgentjar(params.jenkins_user,params.jenkins_pwd,url);
            }

            stage('Oper Remote Host') {
                createRemoteDir(cret, params.host, workDir)
                scpFileToNode(
                        params.jenkins_user ,
                        params.jenkins_pwd,
                        params.jenkins_url,
                        params.nodeLabel,
                        workDir,
                        params.host)
             }
            stage('Notify DeployCentral'){
                status = 30071 //创建服务器成功
                notifyDeployCentral(status)
            }
        }
    }catch (exc) {
        echo 'Create Server Error !'
        status = 30070 //创建服务器失败
        notifyDeployCentral(status)
        throw exc
    }
}

def execurl(jenkins_user,jenkins_pwd,groovy_script){
    sh "curl --user '${jenkins_user}:${jenkins_pwd}' --data-urlencode  'script=${groovy_script}' -X POST '${jenkins_url}'/scriptText"
}

def deleteNode(nodeName){
    def groovy_script = """
       Node node = Jenkins.instance.getNode(\"${nodeName}\")
       println("---- Shutting down node ----!");
       node.getComputer().setTemporarilyOffline(true,null);
       node.getComputer().doDoDelete();
       """
    execurl(params.jenkins_user,params.jenkins_pwd,groovy_script);
}

def deleteOfflineNode(nodeName){
    def groovy_script = """
            for (Node aSlave in Jenkins.instance.getNodes()) {
            println("");
            println("==========");
            println("Name: " + aSlave.name);
            println("computer.isOffline: " + aSlave.getComputer().isOffline());
            println("computer.getLog: " + aSlave.getComputer().getLog());
            println("computer.getBuilds: " + aSlave.getComputer().getBuilds());
            if (aSlave.getComputer().isOffline()) {
              println("----- Shutting down node -----!");
              aSlave.getComputer().setTemporarilyOffline(true,null);
              aSlave.getComputer().doDoDelete();
            }
        }
       """
    execurl(params.jenkins_user,params.jenkins_pwd,groovy_script);
}

def addNode(node_name,executor_count,workDir){
    def groovy_script = """ 
               import hudson.model.Node.Mode
               import hudson.slaves.*
               import jenkins.model.Jenkins
               DumbSlave slave = new DumbSlave(
                                    \"${node_name}\",
                                    \"${node_name}\",
                                    \"${workDir}\",
                                    \"${executor_count}\",
                                    Node.Mode.NORMAL,
                                    \"${node_name}\",
                                    new JNLPLauncher(),
                                    RetentionStrategy.INSTANCE)
                Jenkins.instance.addNode(slave)
                """
    execurl(params.jenkins_user,params.jenkins_pwd,groovy_script);
}

def getAgentjar(jenkins_user,jenkins_pwd,url){
    sh """
     curl --user '${jenkins_user}:${jenkins_pwd}'  '${url}' -o agent.jar
     pwd
     ls
     """
}

def createRemoteDir(cret,host,dir){
    sshagent (credentials: [cret]) {
        sh "su tomcat -c \"ssh -o StrictHostKeyChecking=no tomcat@${host} mkdir -p ${dir}/remoting\""
    }
}

def scpFileToNode(jenkins_user,jenkins_pwd,jenkins_url,node_name,workDir,host){
    def res = sh(script: "su tomcat -c \"ssh tomcat@${host} \'ps -ef | grep -w jenkins-agent | grep -v grep | wc -l\'\"",returnStdout: true).trim()
    if(res as int == 0){
        def secretKey = sh(script: "curl --user '${jenkins_user}:${jenkins_pwd}' -X GET '${jenkins_url}'/computer/'${node_name}'/slave-agent.jnlp | sed \"s/.*<application-desc main-class=\\\"hudson.remoting.jnlp.Main\\\"><argument>\\([a-z0-9]*\\\\).*/\\1/\"",returnStdout: true).trim()
        println(secretKey)
        println("")
        sh """
          echo 'nohup java -jar ${workDir}/agent.jar -jnlpUrl ${jenkins_url}/computer/${node_name}/slave-agent.jnlp -secret ${secretKey} -workDir \"${workDir}\" -failIfWorkDirIsMissing > log 2>&1 &' > start.sh
          ls
          chmod 755 start.sh
          su tomcat -c \"scp agent.jar start.sh tomcat@${host}:${workDir}\"
          su tomcat -c \"ssh -o StrictHostKeyChecking=no tomcat@${host} < 'start.sh'\"
        """
    }
    //ssh -o StrictHostKeyChecking=no ${host} chown -R tomcat:tomcat ${workDir}
}

def notifyDeployCentral(status){
    stage("Notify DeployCentral"){
        echo "Notify DeployCentral: "+status
        def response = httpRequest(url:"${params.callBackHost}/deploy-central/prod/jenkins/notify?callBackId=${params.callBackId}&status=${status}&buildId=${BUILD_ID}&action=${JOB_NAME}@${params.nodeLabel}",timeout: 10)
        println('Status: '+response.status)
    }
}